'''
Case Type： 故障&可靠性测试
Case Name： 数据库备节点数据盘满，主备切换；
Create At: 2020/07/20
@zou_jialiang0505328114
Descption:
步骤 1.启动主备数据库，判断数据库状态；
步骤 2.使用cfe工具，备节点数据库数据盘满；
步骤 3.主备切换；
'''
import os
import unittest
import _thread
import time
from yat.test import macro
from yat.test import Node
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Deletaduit(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case154.py start------------')
        self.rootNode = Node()
        self.startCmd = f'source {macro.DB_ENV_PATH};gs_om -t start'
        self.statusCmd = f'source {macro.DB_ENV_PATH};gs_om -t status --detail'
        self.dbUserNode1 = Node(node='PrimaryDbUser')
        self.dbUserNode = Node(node='PrimaryRoot')
        self.dbUserNode2 = Node(node='Standby1Root')
        self.dbUserNode3 = Node(node='Standby1DbUser')

    def test_startdb(self):
        sourcecmd = f'source {macro.DB_ENV_PATH}'
        switchovercmd = f'{sourcecmd};gs_ctl switchover -D {macro.DB_INSTANCE_PATH}'
        # 使用cfe工具，备节点数据库数据盘满；
        self.log.info("-----------get standby disk name -----------")
        cmd = f"df -h {macro.DB_INSTANCE_PATH}"
        self.log.info(cmd)
        msg = self.dbUserNode2.sh(cmd).result()
        self.log.info(msg)
        disk_name = msg.splitlines()[-1].split()[0].strip()

        cfecmd1 = macro.CFE_PATH + '/./cfe \"inject rfile_full (diskname) values(' + disk_name + ')\"'
        cfecmd2 = macro.CFE_PATH + '/./cfe \"clean  rfile_full  where(diskname=' + disk_name + ')\"'
        self.log.info(cfecmd1)
        self.dbUserNode2.sh(cfecmd1)
        dfmsg = self.dbUserNode2.sh('df -h').result()
        self.log.info(dfmsg)
        self.assertIn('100%', dfmsg)
        # 主备切换；
        msg1 = self.dbUserNode3.sh(switchovercmd).result()
        self.log.info(msg1)
        self.assertIn('No space left on device', msg1)
        self.log.info(cfecmd2)
        self.dbUserNode2.sh(cfecmd2)
        status = self.dbUserNode1.sh(self.statusCmd).result()
        self.log.info(status)

    def tearDown(self):
        self.dbUserNode1.sh(self.startCmd)
        status = self.dbUserNode1.sh(self.statusCmd).result()
        if not status:
            raise Exception("db status is not true, please check!")
        else:
            pass
        self.log.info(
            '------------------------------------reliability_dbsys154.py finish------------------------------------')
